package com.zzh.core.exception;

import common.dto.CommonResponse;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * Created by zhuxh on 16/8/17.
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

  private final Logger logger = LoggerFactory.getLogger(this.getClass());

  @ExceptionHandler(value = Exception.class)
  @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
  public CommonResponse defaultErrorHandler(HttpServletRequest request, Exception e) {
    logger.error("internal error", e);
    CommonResponse response = new CommonResponse(500, e.getMessage());
    return response;
  }

  @ExceptionHandler(value = {NoHandlerFoundException.class})
  @ResponseStatus(HttpStatus.NOT_FOUND)
  public CommonResponse noHandlerFoundException(HttpServletRequest request, Exception ex) {
    logger.error("no handler mapping found {}", request.getRequestURI());
    CommonResponse response = new CommonResponse(404, "uri not found");
    return response;
  }
}
